import {
  asyncRouterMap,
} from '@/router'


import url from '@/url'
import axios from '@/axios'

const permission = {
  state: {
    addRouters: [],
    roles: false,
    entId: '',
    openid: '',
    mainAccount: '',
    role: [],
    errorText: 'loading...'
  },
  mutations: {
    SET_ERRORTEXT: (state, p) => {
      state.errorText = p
    },
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
    },
    SET_ROLES: (state) => {
      state.roles = true
    }

  },
  actions: {
    // 生成新权限列表
    GenerateRoutes({
      state,
      commit
    }) {
      return new Promise(resolve => {
        let accessedRouters = filterAsyncRouter(asyncRouterMap, state.role)
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    },
    // 获取权限列表
    GetRoutes({
      state,
      commit
    }, data) {
      return new Promise((resolve, reject) => {
        axios.post(url.Eelec + '/menu/queryMenuListByOpenId', {
          "entId": state.entId,
          "openId": state.openid,
          "mainAccount": state.mainAccount
        }).then(response => {
          if(response.data.data.length){
            state.role = response.data.data
            resolve(response)
          }else{
            commit('SET_ERRORTEXT', '权限列表为空')
          }
    
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetUserInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        axios.get(url.login + '/web/userEnt/' + sessionStorage.getItem('ticket')).then(response => {
          if (response.data.data.products.includes('EMS')) {
            state.entId = response.data.data.entId
            state.openid = response.data.data.openid
            state.mainAccount = response.data.data.main
            resolve(response)
          }else{
            commit('SET_ERRORTEXT', '没有用户侧权限')
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取能源类型
    GetCustMeterFlag({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        axios.get(url.Eelec + '/index/getCustMeterFlag', {
          params: {
            "custId": sessionStorage.getItem('custId')
          }
        }).then(response => {
          const typeArrr = []
          typeArrr.push(response.data.data.electric)
          typeArrr.push(response.data.data.steam)
          sessionStorage.setItem('EnergyType', JSON.stringify(typeArrr))
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取id
    GetUser({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        axios.post(url.Eelec + '/index/getUser', {
          "ticket": sessionStorage.getItem('ticket')
        }).then(response => {
          if(response.data.data.custId){
            sessionStorage.setItem('custId', response.data.data.custId)
            sessionStorage.setItem('entName', response.data.data.entName)
            sessionStorage.setItem('realname', response.data.data.realname)
            resolve(response)
          }
          else{
          commit('SET_ERRORTEXT', '获取用户ID失败')
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
  }
}

export default permission


function filterAsyncRouter(routes, roles) {
  const res = asyncRouterMap
  let arr = []
  for (let i = 0; i < res.length; i++) {
    for (let j = 0; j < roles.length; j++) {
      if (res[i].meta.title === roles[j].itemMenu.name) {
        arr.push({
          'children': [],
          'component': res[i].component,
          'meta': res[i].meta,
          'name': res[i].name,
          'path': res[i].path,
          'redirect': res[i].redirect,
        })
        for (let m = 0; m < res[i].children.length; m++) {
          for (let n = 0; n < roles[j].subMenus.length; n++) {
            if (res[i].children[m].meta.title === roles[j].subMenus[n].name) {
              arr[i].children.push(res[i].children[m])
            }
          }
        }
      }
    }
  }
  arr.push({
    path: '/index',
    name: 'index',
    hidden: true,
    component: () =>
      import('@/views/index/index'),
    meta: {
      title: '首页',
      icon: 'iconfont icon-fenxi'
    },
  }, {
    path: '*',
    redirect: '/index',
    hidden: true,
  })
  return arr
}